package org.gitee.weapp.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.gitee.weapp.domain.entity.SysUser;
import org.gitee.weapp.mapper.SysUserMapper;
import org.gitee.weapp.service.SysUserService;
import org.gitee.weapp.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    @Override
    public void uploadAvatar(SysUser sysUser, MultipartFile multipartFile) {
        File avatarPath = new File(new File("").getAbsolutePath() + "/avatar");
        if (!avatarPath.exists()) {
            avatarPath.mkdirs();
        }

        try {
            File file = new File(avatarPath.getAbsolutePath() + '/' + sysUser.getOpenId());
            file.createNewFile();
            multipartFile.transferTo(file.getAbsoluteFile());
            String avatarUrl = "/user/getAvatar?userId=" + sysUser.getOpenId();
            sysUser.setAvatarUrl(avatarUrl);
            sysUserMapper.update(sysUser);
            tokenService.refreshToken(sysUser, true);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void getAvatar(String userId, HttpServletResponse response) {
        File avatarPath = new File(new File("").getAbsolutePath() + "/avatar");
        if (avatarPath.exists()) {
            try(InputStream input = Files.newInputStream(Paths.get(
                    avatarPath.getAbsolutePath() + '/' + userId));
                ServletOutputStream output = response.getOutputStream()) {
                IOUtils.copy(input,output);
            } catch (Exception e) {
                log.error("获取用户头像出错:", e);
            }
        }
    }
}
